package DAO.JavaDAO;

import DAO.JavaBean.CustomerBean;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class CustomerDAO {
    private Connection connection;

    public CustomerDAO() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/test";
            connection = DriverManager.getConnection(url, "Lingqin", "123456");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //查询
    public ResultSet search(String custName) throws SQLException {
        List<CustomerBean> customers = new ArrayList<CustomerBean>();
        Statement statement = connection.createStatement();
        String sql = "select * from customer ";
        if (!custName.equals("")) {
            sql = sql + "where custName =" + custName;
        }

        return statement.executeQuery(sql);
    }

    public ResultSet result() throws SQLException {
        Statement stmt = connection.createStatement();
        String sql = "select * from customer";
        return stmt.executeQuery(sql);
    }


    //插入
    public boolean insertCustomer(CustomerBean customer) throws SQLException {
        Statement statement = connection.createStatement();
        String sql = "insert into customer values ('" + customer.getCustName() + "','" + customer.getEmail() + "','" + customer.getPhone() + "')";
        boolean rs = statement.execute(sql);
        return !rs;
    }

    //修改
    public boolean update(CustomerBean customer) throws SQLException {
        Statement statement = connection.createStatement();
        String sql = "update customer set email='" + customer.getEmail() +  "',phone='"+customer.getPhone()+"' where custName= '" + customer.getCustName()+"'";
        boolean rs = statement.execute(sql);
//        System.out.println(rs);
        return !rs;
    }

    //删除
    public boolean deleteCustomer(String customer) throws SQLException {
        Statement statement = connection.createStatement();
        String sql = "delete from customer where custName='" + customer+"'";
        boolean rs = statement.execute(sql);
        return !rs;
    }

    //关闭连接
    public void destoryConnection() throws SQLException {
        connection.close();
    }
}
